package com.dlc.shop.coupon.common.listener;

import com.dlc.shop.bean.app.dto.CouponDto;
import com.dlc.shop.bean.enums.CouponProdType;
import com.dlc.shop.bean.event.EsProductCouponInfoEvent;
import com.dlc.shop.bean.vo.search.ProductSearchVO;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.coupon.common.model.Coupon;
import com.dlc.shop.coupon.common.model.CouponProd;
import com.dlc.shop.coupon.common.service.CouponService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: zsm
 * @date: 2023/3/13 15:06
 */
@Component("esProductCouponInfoListener")
@AllArgsConstructor
public class EsProductCouponInfoListener {

    private final CouponService couponService;

    @EventListener(EsProductCouponInfoEvent.class)
    public void esProductCouponInfoListener(EsProductCouponInfoEvent event){
        List<ProductSearchVO> productList = event.getProductList();
        productList.stream().map(ProductSearchVO::getShopId).collect(Collectors.toList());
        for(ProductSearchVO productSearchVO : productList){
            // 获取已投放优惠券
            List<Coupon> couponList = couponService.listPutonByShopId(productSearchVO.getShopId());
            // 过滤商品
            couponList = couponList.stream().filter(a -> {
                boolean flag = true;

                if (a.getGetWay() == null) {
                    // 如果getWay为空，默认当成0处理
                    a.setGetWay(0);
                } else if (a.getGetWay() == 1) {
                    // 不是用户直接领取的优惠券，直接不显示该优惠券
                    return false;
                }
                //过滤指定商品不参与
                if (Objects.equals(a.getSuitableProdType(), CouponProdType.PROD_NO_IN.value())) {
                    for (CouponProd couponProd : a.getCouponProds()) {
                        if (Objects.equals(couponProd.getProdId(), productSearchVO.getProdId())) {
                            flag = false;
                            break;
                        }
                    }
                }
                //过滤指定商品参与
                else if (Objects.equals(a.getSuitableProdType(), CouponProdType.PROD_IN.value())) {
                    flag = false;
                    for (CouponProd couponProd : a.getCouponProds()) {
                        if (Objects.equals(couponProd.getProdId(), productSearchVO.getProdId())) {
                            flag = true;
                            break;
                        }
                    }
                }
                return flag;
            }).collect(Collectors.toList());
            productSearchVO.setCouponDtos(BeanUtil.mapAsList(couponList, CouponDto.class));
        }

    }
}
